package co.za.itweb.securedata;


import java.io.File;
import java.util.ArrayList;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Second extends FragmentActivity{
	
	private static final int ID_MYNEWS = 1;
	private static final int ID_SECTORNEWS = 2;
	private static final int ID_FINDUS = 3;
	private static final int ID_ABOUTUS = 4;
	private static final int ID_MYWEB = 5;
	ArrayList<String> updated;
	 
	
	
	
	LazyLoadImage icondownloader;
	HorizontalScrollView hsv;
	ImageView topbaricon;
	static String[] titles;
	static String[] images;
	static String[] bigimages;
	static String[] story;
	static String[] published;
	static String[] summary;
	static String[] author;
	String title;
	ListView list;
	LazyAdapter2 adapter;
	 int feedValue;
	int WindowWidth;
	static Dialog dialog;
	ProgressDialog progressDialog;
	RSSFeed feed;
	 QuickAction mQuickAction;
	private String density;
	static ArrayList<RSSFeed> FavoriteList = new ArrayList<RSSFeed>(0);
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.first);
		
		feedValue=1;
		
		
//		ViewTreeObserver viewTreeObserver = hsv.getViewTreeObserver();
//		  if (viewTreeObserver.isAlive()) {
//		    viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
//		      @Override
//		      public void onGlobalLayout() {
//		        hsv.smoothScrollTo(100,0);
//		      }
//		    });
//		  }
		

				if ( First.List.size() == 0 || First.jArray==null) {

			Intent intent = new Intent(getApplicationContext(),
					Splash.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivityForResult(intent, 1);

		} else {
			populate();
		
		
		}
	}
	
	
	public String determineDensity(){
		switch (getResources().getDisplayMetrics().densityDpi) {
		case DisplayMetrics.DENSITY_LOW:
			density="ldpi";
		    break;
		case DisplayMetrics.DENSITY_MEDIUM:
			density= "mdpi";
			 break;
		case DisplayMetrics.DENSITY_HIGH:
			density= "hdpi";
			 break;
		case DisplayMetrics.DENSITY_XHIGH:
			density= "xdpi";
			 break;
		}
		return density;
	}
	
	private void populate() {

		
		

		ActionItem mynews = new ActionItem(ID_MYNEWS,  First.PAGE1TITLE,getDrawableFromSD(First.mynewsname, getResources()
				.getDrawable(R.drawable.mynews) ));
		

		

//		ActionItem sectornews = new ActionItem(ID_SECTORNEWS, "Sector News",
//				getDrawableFromSD("myweb.png", getResources()
//						.getDrawable(R.drawable.ic_up) ));
		ActionItem findus = new ActionItem(ID_FINDUS,  First.PAGE3TITLE, getDrawableFromSD(First.findusname, getResources()
				.getDrawable(R.drawable.findus) ));
		ActionItem aboutus = new ActionItem(ID_ABOUTUS,  First.PAGE4TITLE,
				getDrawableFromSD(First.aboutusname, getResources()
						.getDrawable(R.drawable.aboutus) ));
		ActionItem myweb = new ActionItem(ID_MYWEB,  First.PAGE5TITLE, getDrawableFromSD(First.mywebname, getResources()
				.getDrawable(R.drawable.myweb) ));

		// uploadItem.setSticky(true);

		mQuickAction = new QuickAction(getApplicationContext(),QuickAction.VERTICAL);

		
		
		mQuickAction.addActionItem(mynews);
//		mQuickAction.addActionItem(sectornews);
		mQuickAction.addActionItem(findus);
		mQuickAction.addActionItem(aboutus);
		mQuickAction.addActionItem(myweb);
		
		
		
		//setup the action item click listener
		mQuickAction
		.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
			@Override
			public void onItemClick(QuickAction quickAction, int pos,
					int actionId) {
				

				if (actionId == ID_SECTORNEWS) {
					Intent intent = new Intent(getApplicationContext(),
							Second.class);

					intent.putExtra("feedid", feedValue);

					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);

				}else if (actionId == ID_MYNEWS) {
					Intent intent = new Intent(getApplicationContext(),
							First.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);

				} 
				
				else if (actionId == ID_FINDUS) {
					Intent intent = new Intent(getApplicationContext(),
							DialogActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);

				} else if (actionId == ID_MYWEB) {
					Intent intent = new Intent(getApplicationContext(), MyWeb.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);

				}

				else if (actionId == ID_ABOUTUS) {
					Intent intent = new Intent(getApplicationContext(), About.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
				} else {

				}
			}
		});
		
		mQuickAction.setOnDismissListener(new QuickAction.OnDismissListener() {
			@Override
			public void onDismiss() {
//				Toast.makeText(getApplicationContext(), "Ups..dismissed", Toast.LENGTH_SHORT).show();
			}
		});
		
		LinearLayout backgroundlayout = (LinearLayout) findViewById(R.id.background);
		backgroundlayout.setBackgroundColor(Color.parseColor(First.BACKGROUND));
		LinearLayout layout = (LinearLayout) findViewById(R.id.cell1);
		if(First.STARTCOLOR.length()>3 && First.ENDCOLOR.length() >3){ 
	    int colors[] =  {Color.parseColor(First.STARTCOLOR),Color.parseColor(First.ENDCOLOR)};
		GradientDrawable grad = new GradientDrawable(Orientation.TOP_BOTTOM,colors);
		layout.setBackgroundDrawable(grad);
		
		}
		
		topbaricon = (ImageView) findViewById(R.id.title);
		icondownloader = new LazyLoadImage(topbaricon);
		Bitmap avatar = icondownloader.getBitmapFromCache(First.PATH +"images/"+ determineDensity()
				 +"/"+First.LOGONAME);
		if(avatar==null){
			icondownloader.execute(First.PATH +"images/"+ determineDensity()
					 +"/"+First.LOGONAME);
		}else{
			topbaricon.setImageBitmap(avatar);
		}
		
			
		
		
	        Button favorites=(Button) findViewById(R.id.cell1).findViewById(R.id.favorites);
	        favorites.setVisibility(View.GONE);
	        
	        Button refresh=(Button) findViewById(R.id.cell1).findViewById(R.id.refresh);
	        refresh.setBackgroundDrawable(getDrawableFromSD(First.refreshname, getResources()
					.getDrawable(R.drawable.ic_refresh) ));
	        
	        TextView titletext = (TextView) findViewById(R.id.page);
			titletext.setText(First.PAGE2TITLE);
			titletext.setTextColor(Color.parseColor(First.LISTTEXTCOLOR));
			titletext.setPaintFlags(titletext.getPaintFlags() |   Paint.UNDERLINE_TEXT_FLAG);
		
            Button menu=(Button) findViewById(R.id.cell1).findViewById(R.id.menu);
            menu.setBackgroundDrawable(getDrawableFromSD(First.menuname, getResources()
    				.getDrawable(R.drawable.menu) ));
			 menu.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						
						
						mQuickAction.show(v);
						mQuickAction.setAnimStyle(QuickAction.ANIM_GROW_FROM_RIGHT);
						
					}
				});
	       
		 
		
		 
		 refresh.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(Second.this, Refresh.class);
					startActivityForResult(intent, 2);
					

				
				}
			});
		 
		 
		 
		
		 
		
		 
		 
		 if (First.List.size()==0) {
				Toast.makeText(getApplicationContext(), "Feed is not loaded",
						Toast.LENGTH_LONG).show();
				Intent intent1 = new Intent(getApplicationContext(), SingleNews.class);
				intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent1);
			} else {
				
				
				titles = new String[First.List.get(feedValue)._itemlist
						.size()];
				images = new String[First.List.get(feedValue)._itemlist
						.size()];
				bigimages = new String[First.List.get(feedValue)._itemlist
						.size()];
				story = new String[First.List.get(feedValue)._itemlist
						.size()];
				published = new String[First.List.get(feedValue)._itemlist
						.size()];
				summary = new String[First.List.get(feedValue)._itemlist
						.size()];
				author = new String[First.List.get(feedValue)._itemlist
						.size()];

				for (int i = 0; i < First.List.get(feedValue)._itemlist
						.size(); i++) {
					if (First.List.get(feedValue)._itemlist.get(i)
							.getTitle() != null) {
						titles[i] = First.List.get(feedValue)._itemlist
								.get(i).getTitle();
					} else {
						titles[i] = "";
					}
					if (First.List.get(feedValue)._itemlist.get(i)
							.getImage() != null) {
						images[i] = First.List.get(feedValue)._itemlist
								.get(i).getImage();
					} else {
						images[i] = "";
					}

					if (First.List.get(feedValue)._itemlist.get(i)
							.getbigImage() != null) {
						bigimages[i] = First.List.get(feedValue)._itemlist
								.get(i).getbigImage();
					} else {
						bigimages[i] = "";
					}
					if (First.List.get(feedValue)._itemlist.get(i)
							.getStory() != null) {
						story[i] = First.List.get(feedValue)._itemlist
								.get(i).getStory().toString();
					} else {
						story[i] = "";
					}
					if (First.List.get(feedValue)._itemlist.get(i)
							.getpubDate() != null) {
						published[i] = First.List.get(feedValue)._itemlist
								.get(i).getpubDate();
					} else {
						published[i] = "";
					}
					if (First.List.get(feedValue)._itemlist.get(i)
							.getSummary() != null) {
						summary[i] = First.List.get(feedValue)._itemlist
								.get(i).getSummary();
					} else {
						summary[i] = "";
					}
					if (First.List.get(feedValue)._itemlist.get(i)
							.getAuthor() != null) {
						author[i] = First.List.get(feedValue)._itemlist
								.get(i).getAuthor();
					} else {
						author[i] = "";
					}
				}

				list = (ListView) findViewById(R.id.list);
				adapter = new LazyAdapter2(this, images);
				list.setAdapter(adapter);
				list.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						Intent intent = new Intent(getApplicationContext(),
								SingleNews.class);
						intent.putExtra("id", position);
						intent.putExtra("feedid", feedValue);
						overridePendingTransition(R.anim.hold, R.anim.pull_in_from_left);
						startActivity(intent);
					}
				});

			}
		
	}

	
	public Drawable getDrawableFromSD(String imagename, Drawable defaultdrawable){
		File path = new File( Environment.getExternalStorageDirectory()+"/"+First.FOLDERNAME+"/"+imagename);
		 if(path.exists() ) {
		try{
		Bitmap bitmapImage = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+"/"+First.FOLDERNAME+"/"+imagename);
		Drawable bgrImage;
        bgrImage = new BitmapDrawable(getResources(),bitmapImage);
		   
		   return bgrImage;
		   
		}catch(Exception ex){
			System.out.println(ex.toString());
			return defaultdrawable;
		}
		 }else{
			 return defaultdrawable;
		 }
	   }
	
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		System.out.println("RESULT CODE"+resultCode +" REQUEST CODE "+requestCode+" DATA "+data);

		if (requestCode == 1) {

			if (resultCode == RESULT_OK) {
				try{
					First.STARTCOLOR=First.jArray.getString("startcolor");
					First.ENDCOLOR=First.jArray.getString("endcolor");
					First.PATH=First.jArray.getString("logopath");
					populate();
					Toast.makeText(getApplicationContext(),
							"News are refreshed...", Toast.LENGTH_SHORT).show();
				}catch(Exception ex){
					System.out.println(ex.toString());
				}
			}
				
				
			
			if (resultCode == RESULT_CANCELED) {
				Toast.makeText(getApplicationContext(),
						"There was mistake while refreshing...", Toast.LENGTH_SHORT).show();
				finish();		

			}
			
			
		}
		
		if(requestCode==2){
			
			if (resultCode == RESULT_OK) {
				adapter.notifyDataSetChanged();
				Toast.makeText(getApplicationContext(),
						"News are refreshed...", Toast.LENGTH_SHORT).show();
			}

			if (resultCode == RESULT_CANCELED) {
				Toast.makeText(getApplicationContext(),
						"There was mistake while refreshing...", Toast.LENGTH_SHORT).show();
				

			}
		}
			
	}
	
	
	@Override
	protected void onPause() {
		// Whenever this activity is paused (i.e. looses focus because another
		// activity is started etc)
		// Override how this activity is animated out of view
		// The new activity is kept still and this activity is pushed out to the
		// left
		
		if(mQuickAction != null && mQuickAction.mWindow.isShowing()){
			mQuickAction.dismiss();
		
		}
		
		if (dialog != null && dialog.isShowing()) {
			dialog.dismiss();
		}
		overridePendingTransition(R.anim.hold, R.anim.push_out_to_left);
		super.onPause();
	}

	
	
	
		

	

		
	
	
	
	
	
	
}
